package com.dsunsoft.rtu.service.impl;

import com.dsunsoft.rtu.entity.Subject;
import com.dsunsoft.rtu.enums.SubjectType;
import com.dsunsoft.rtu.service.ToolService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
public class ToolServiceImpl implements ToolService {

    @Override
    public List<Subject> pdfToExcel(MultipartFile file) {
        List<Subject> result = new ArrayList<>();
        if(file.isEmpty()){
            log.info("上传txt文件为空！");
            return result;
        }
        try {
            List<String> textList = readTextMultipartFile(file);
            result = parseTextList(textList);
        } catch (Exception e){
             log.error("读取解析文件出错："+e.getMessage());
        }
        if(result == null || result.size() == 0){
            log.info("读取解析题目为空！");
            return new ArrayList<>();
        }
        for (Subject subject:result) {
            List<String> optionList = subject.getOptionList();
            if(optionList != null){
                if(optionList.size()>0){
                    subject.setOptionA(optionList.get(0));
                }
                if(optionList.size()>1){
                    subject.setOptionB(optionList.get(1));
                }
                if(optionList.size()>2){
                    subject.setOptionC(optionList.get(2));
                }
                if(optionList.size()>3){
                    subject.setOptionD(optionList.get(3));
                }
                if(optionList.size()>4){
                    subject.setOptionE(optionList.get(4));
                }
                if(optionList.size()>5){
                    subject.setOptionF(optionList.get(5));
                }
                if(optionList.size()>6){
                    subject.setOptionG(optionList.get(6));
                }
                if(optionList.size()>7){
                    subject.setOptionH(optionList.get(7));
                }
                if(optionList.size()>8){
                    subject.setOptionI(optionList.get(8));
                }
                if(optionList.size()>9){
                    subject.setOptionJ(optionList.get(9));
                }
                if(optionList.size()>10){
                    subject.setOptionK(optionList.get(10));
                }
            }
        }
        return result;
    }

    // 转换读取的文本
    public static List<Subject> parseTextList(List<String> textList){
        List<Subject> result = new ArrayList<>();
        if(textList == null || textList.size() == 0){
            log.info("解析题目txt为空！");
            return result;
        }
        // 当前题型
        String subType = "1";
        // 当前题号码
        Integer subNum = 0;
        Subject subject= null;
        //当前是解析的是题干还是选项
        // 1 ：题干  2：选项
        String lineType = "1";
        // 上一行
        String preLine = "";
        // 上一个题干
        String preSubContent = "";
        // 上一个题目选项
        String preOptionContenet = "";
        // 是否开始题目行
        Boolean isStartSubject = false;
        for (int i =0;i<textList.size();i++){
            // 当前行
            String line = textList.get(i);
            // 下一行
            String nextLine = null;
            if(i < textList.size()-1){
                nextLine = textList.get(i+1);
            }
            // 空的忽略
            if(line == null || "".equals(line)){
                continue;
            }
            line = line.trim();
            //
            if(!isStartSubject && (startsWithChinesePrefix(line))){
                isStartSubject = true;
            }
            // 题目开始
            if(isStartSubject){
                // 判断题型
                if(startsWithChinesePrefix(line) && line.contains("单选题")){
                    subType = "1";
                    continue;
                }
                if(startsWithChinesePrefix(line) &&  line.contains("多选题")){
                    subType = "2";
                    continue;
                }
                if(startsWithChinesePrefix(line) &&  line.contains("判断题")){
                    subType = "3";
                    continue;
                }

                // 需要判断当前行是题干还是选项，还是换行接上一行的
                if(startsWithDigit(line)){
                    // 本行是题干开头
                    lineType = "1";
                    // 添加一道题
                    subject = new Subject();
                    subNum +=1;
                    subject.setSubNum(subNum.toString());
                    subject.setSubType(subType);
                    subject.setSubTypeName(SubjectType.getName(subType));
                    // 题干和答案在一行
                    String subjectNum = "";
                    String answer = "";
                    List<String> subjectNumList = getSubjectNum(line);
                    if(subjectNumList.size()>0){
                        subjectNum = subjectNumList.get(0);
                        subject.setSubNum(subjectNum);
                    }
                    if(isAnswer(line, subType)){
                        List<String> answerList = getAnswerContents(line, subType);
                        if(answerList.size()>0){
                            answer = answerList.get(0);
                        }
                        subject.setSubAnswer(getAnswerBySubType(answer,subType));
                        String lineSubContent = line.replace(answer,"")
                                .replace("(","")
                                .replace(")","")
                                .replace("（","")
                                .replace("）","")
                                .replace(subjectNum,"")
                                .replaceFirst(".","")
                                ;
                        subject.setSubContent(lineSubContent);
                        result.add(subject);
                        preSubContent = "";
                    }
                    else {
                        // 本行答案和题干不在一行
                        preSubContent =  line.replace(subjectNum,"")
                                .replaceFirst(".","");
                    }
                } else if(isSubOption(line)){
                    // 本行是选项开头
                    lineType = "2"; // 本行是选项
                    String optionType = "";// 选项
                    String optionContenet = "";
                    List<String> subjectOptionList = getSubjectOption(line);
                    if(subjectOptionList.size()>0){
                        optionType = subjectOptionList.get(0);
                    }
                    optionContenet = line.replace(optionType,"")
                            .replaceFirst(".", "");
                    if(nextLine != null &&
                            (startsWithChinesePrefix(nextLine) || startsWithDigit(nextLine) || isSubOption(nextLine))){
                        subject.getOptionList().add(optionContenet);
                        preOptionContenet = "";
                    } else {
                        preOptionContenet = optionContenet;
                    }
                }
                else {
                    // 含有结答案
                    if(isAnswer(line, subType)){
                        String answer = "";
                        List<String> answerList = getAnswerContents(line, subType);
                        if(answerList.size()>0){
                            answer = answerList.get(0);
                        }
                        subject.setSubAnswer(getAnswerBySubType(answer,subType));
                        String lineSubContent = line.replace(answer,"")
                                .replace("(","")
                                .replace(")","")
                                .replace("（","")
                                .replace("）","");
                        preSubContent +=lineSubContent;
                        subject.setSubContent(preSubContent);
                        result.add(subject);
                        preSubContent = "";
                    } else {
                        if("1".equals(lineType)){
                            // 题干
                            preSubContent += line;
                        }
                        if("2".equals(lineType)){
                            // 题目选项
                            preOptionContenet += line;
                            if(nextLine != null &&
                                    (startsWithChinesePrefix(nextLine) || startsWithDigit(nextLine) || isSubOption(nextLine))) {
                                subject.getOptionList().add(preOptionContenet);
                                preOptionContenet = "";
                            }
                        }
                    }
                }
                preLine = line;
            }
        }
        return  result;
    }

    public static String getAnswerBySubType(String answer, String subType) {
        if(SubjectType.单选题.getValue().equals(subType)){
            return answer;
        } else if(SubjectType.多选题.getValue().equals(subType)){
            return insertCommaBetweenChars(answer);
        } else if(SubjectType.判断题.getValue().equals(subType)){
            return ("√".equals(answer) ? "A":  ("×".equals(answer) ? "B": answer));
        } else {
            return answer;
        }
    }

    public static String insertCommaBetweenChars(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }

        // 使用StringBuilder来构建结果字符串，因为它比String更适合字符串的修改
        StringBuilder sb = new StringBuilder();

        // 遍历字符串的每个字符，除了最后一个
        for (int i = 0; i < str.length() - 1; i++) {
            sb.append(str.charAt(i)).append(",");
        }

        // 添加最后一个字符
        sb.append(str.charAt(str.length() - 1));

        // 将StringBuilder转换为String并返回
        return sb.toString();
    }

    public static boolean startsWithChinesePrefix(String str) {
        // 检查字符串是否为空或null
        if (str == null || str.isEmpty()) {
            return false;
        }
        // 检查是否以“一”、“二”、“三”开头
        String[] prefixes = {"一", "二", "三", "四","五", "六", "七", "八", "九", "十"};
        for (String prefix : prefixes) {
            if (str.startsWith(prefix)) {
                return true;
            }
        }
        // 如果不是以这些中文字符开头，则返回false
        return false;
    }

    // 数字开头的为题干
    public static boolean startsWithDigit(String str) {
        // 检查字符串是否为空或null
        if (str == null || str.isEmpty()) {
            return false;
        }
        // 检查第一个字符是否是数字
        boolean fisrtIsNum = Character.isDigit(str.charAt(0));
        return fisrtIsNum && isNumeric(str);
    }


    public static boolean isNumeric(String str) {
        if (str == null) {
            return false;
        }
        String regex = "^([0-9]+)\\.";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        // 如果找到匹配项，则返回true
        return matcher.find();
    }

    public static List<String> getSubjectNum(String text) {
        List<String> contents = new ArrayList<>();
        String regex  = "^([0-9]+)\\.";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            if (matcher.group(1) != null && matcher.start() == 0) {
                contents.add(matcher.group(1));
            }
        }

        return contents;
    }

    public static boolean isSubOption(String str) {
        if (str == null) {
            return false;
        }
        String regex = "^([A-Z]+)\\.";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        // 如果找到匹配项，则返回true
        return matcher.find();
    }

    public static List<String> getSubjectOption(String text) {
        List<String> contents = new ArrayList<>();
        String regex  = "^([A-Z]+)\\.";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            if (matcher.group(1) != null && matcher.start() == 0) {
                contents.add(matcher.group(1));
            }
        }

        return contents;
    }

    public static List<String> getAnswerContents(String text, String subType) {
        List<String> contents = new ArrayList<>();
//        String regex = "\\（([^（）]*)\\）|\\(([^()]*)\\)";
//        String regex = ".*\\（.*\\）$|.*\\(.*\\)$";
        String regex = "(?:（([A-Z]+)）$)|(?:\\(([A-Z]+)\\)$)";
        if("3".equals(subType)){
            regex = "(?:（([^）]+)）$)|(?:\\(([^)]+)\\)$)";
        }
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            if (matcher.group(1) != null) {
                // 匹配到的是中文圆括号内的内容
                contents.add(matcher.group(1));
            } else if (matcher.group(2) != null) {
                // 匹配到的是英文圆括号内的内容
                contents.add(matcher.group(2));
            }
        }

        return contents;
    }


    public static boolean isAnswer(String str, String subType) {
        if (str == null) {
            return false;
        }
            // 正则表达式，匹配中文圆括号“（）”或英文圆括号“()”
//        String regex = "(?:（([^）]+)）$)|(?:\\(([^)]+)\\)$)";
//        String regex = ".*\\（.*\\）$|.*\\(.*\\)$";
        String regex = "(?:（([A-Z]+)）$)|(?:\\(([A-Z]+)\\)$)";
        if("3".equals(subType)){
            regex = "(?:（([^）]+)）$)|(?:\\(([^)]+)\\)$)";
        }
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        // 如果找到匹配项，则返回true
        return matcher.find();
    }

    public static void main(String[] args) {
        String str = "595.漏电保护器与 RCD（ResidualCurrentDevice）的关系是";
        String str2 = "什么？（A）";
        String str3= "型（如平键、楔键、花键等）？（C）";
        String str4= "只要不影响安装即可（×）";


        System.out.println(isAnswer(str, "1"));
        System.out.println(isAnswer(str2, "1"));
        System.out.println(isAnswer(str3, "1"));
        System.out.println(isAnswer(str3, "3"));

        List<String> list1 = getAnswerContents(str, "1");
        List<String> list2 = getAnswerContents(str2, "1");
        List<String> list3 = getAnswerContents(str3, "1");
        List<String> list4 = getAnswerContents(str4, "3");


//        System.out.println(list1.get(0));
        System.out.println(list2.get(0));
        System.out.println(list3.get(0));
        System.out.println(list4.get(0));
    }



    public static List<String>  readText(File file){
        List<String> textList = new ArrayList<>();
        try  {
            FileReader fileReader = new FileReader(file);
            BufferedReader br = new BufferedReader(fileReader);
            String line;
            while ((line = br.readLine()) != null) {
                log.debug(line);
                textList.add(line);
            }
        } catch (Exception e) {
            log.error("读取文件异常："+e.getMessage());
            e.printStackTrace();
        }
        return textList;
    }

    public static List<String>  readTextMultipartFile(MultipartFile file){
        List<String> textList = new ArrayList<>();
        try  {
            BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream(), "UTF-8"));
            String line;
            while ((line = br.readLine()) != null) {
                log.debug(line);
                textList.add(line);
            }
        } catch (Exception e) {
            log.error("读取文件异常："+e.getMessage());
            e.printStackTrace();
        }
        return textList;
    }
}
